package media

import (
    "fmt"
    "io"
    "log"
    "net/http"

    "github.com/gin-gonic/gin"
)

// 定义一个通道来存储视频流数据
var videoStreams = make(chan io.Reader, 10)

// 处理推流请求
func handleHTTPPublish(c *gin.Context) {
    if c.Request.Method != http.MethodPut && c.Request.Method != http.MethodPost {
        c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "Invalid request method"})
        return
    }
    // 检查通道是否已满
    select {
    case videoStreams <- c.Request.Body:
        fmt.Println("Video stream published successfully")
        c.JSON(http.StatusOK, gin.H{"message": "Stream published"})
    default:
        c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Server is busy, try again later"})
        return
    }
    // 在请求处理完成后关闭请求体
    defer c.Request.Body.Close()
}

// 处理拉流请求
func handleHTTPPlay(c *gin.Context) {
    if c.Request.Method != http.MethodGet {
        c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "Invalid request method"})
        return
    }
    select {
    case stream := <-videoStreams:
        // 尝试从请求头中获取 Content-Type，如果没有则默认使用 video/x-flv
        contentType := c.Request.Header.Get("Content-Type")
        if contentType == "" {
            contentType = "video/x-flv"
        }
        c.Writer.Header().Set("Content-Type", contentType)
        // 将视频流数据复制到响应中
        _, err := io.Copy(c.Writer, stream)
        if err != nil {
            log.Printf("Error sending video stream: %v", err)
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Error sending video stream"})
        }
        // 在复制完成后关闭流
        if closer, ok := stream.(io.Closer); ok {
            closer.Close()
        }
    default:
        c.JSON(http.StatusNotFound, gin.H{"error": "No video stream available"})
    }
}

func StartHTTPVideo() {
    // 创建默认的 Gin 引擎，包含日志和恢复中间件
    r := gin.Default()
    // 注册推流处理函数，同时支持 POST 和 PUT 方法
    r.Any("/publish", handleHTTPPublish)
    // 注册拉流处理函数
    r.GET("/playClient", handleHTTPPlay)

    fmt.Println("HTTP video server started on port 8087")
    // 启动服务器，监听 8087 端口
    if err := r.Run(":8087"); err != nil {
        log.Fatalf("Failed to start server: %v", err)
    }
}
